const logger = require('../utils/logger');
const { errorResponse } = require('../utils/response');

// 捕获404错误
exports.notFound = (req, res, next) => {
  errorResponse(res, `接口不存在 - ${req.originalUrl}`, 404);
};

// 全局错误处理中间件
exports.errorHandler = (err, req, res, next) => {
  const statusCode = res.statusCode === 200 ? 500 : res.statusCode;
  
  // 记录错误日志
  logger.error(`${err.message} - ${req.originalUrl} - ${req.method} - ${req.ip}`);
  
  // 如果是开发环境，返回错误堆栈
  const stack = process.env.NODE_ENV === 'production' ? null : err.stack;
  
  errorResponse(res, err.message, statusCode, stack);
}; 